package com.swingson.properties;

import com.swingson.SwingsonGui;
import com.swingson.exceptions.ErrorMessageException;
import com.swingson.exceptions.SkipException;
import com.swingson.exceptions.SwingsonException;
import com.swingson.jsonparser.JsonElement;
import java.lang.reflect.InvocationTargetException;
import javax.swing.JComponent;

/**
 * @author sad
 */
public abstract class BasePropertyProcessor {

    public abstract Object processProperty(JsonElement jsonElement, JComponent component, SwingsonGui gui, String propertyName);

    protected int getIntValue(JsonElement element, String errorMessage) {
        if (!element.isPrimitive()) {
            throw new SwingsonException(errorMessage);
        }
        try {
            int result = element.getAsInt();
            return result;
        } catch (Exception ex) {
            throw new SwingsonException(errorMessage, ex);
        }
    }

    protected interface EventExecutor<T> {

        public void execute(T event);
    }

    protected void onError(SwingsonGui gui, Throwable throwable) {
        if (throwable instanceof SkipException) {
            return;
        }
        if (throwable instanceof InvocationTargetException) {
            if (((InvocationTargetException) throwable).getTargetException() instanceof SkipException) {
                return;
            }
            gui.onException(((InvocationTargetException) throwable).getTargetException());
        } else if (throwable instanceof ErrorMessageException) {
            gui.onException(throwable);
        } else {
            throw new RuntimeException(throwable);
        }
    }
}
